/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.InputStream;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;
import javax.microedition.media.Manager;
import javax.microedition.media.Player;
import javax.microedition.midlet.*;

/**
 * @author Administrador
 */
public class AudioTest extends MIDlet implements CommandListener {
    private Display display;
    private Form form;
    private StringItem duracion;
    private TextField inicio, fin;
    private Command exitCmd, okCmd;
    private InputStream is;
    private Player player;


    public void startApp() {
        initUI();
        initPlayer();
        int seg =  (int) (player.getDuration() * 0.000001);
        duracion.setText(String.valueOf(seg));
        fin.setString(String.valueOf(seg));
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }

    public void commandAction(Command c, Displayable d) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    private void initPlayer() {
        try{
            is = getClass().getResourceAsStream("/54321.mp3");
            player = Manager.createPlayer(is, "audio/mpeg");
            player.realize();
            player.prefetch();
        }catch(Exception e){manageException(e);}
    }

    private void initUI(){
        display = Display.getDisplay(this);

        exitCmd = new Command("Salir", Command.EXIT, 2);
        okCmd = new Command("Ok", Command.OK, 0);

        form = new Form("AudioTest");
        duracion = new StringItem("Duración del Fichero:", "");
        form.append(duracion);
        inicio = new TextField("Tiempo de Inicio:", "00", 2, 2);
        form.append(inicio);
        fin = new TextField("Tiempo de Fin:", "", 2, 2);
        form.append(fin);
        form.addCommand(exitCmd);
        form.addCommand(okCmd);

        form.setCommandListener(this);

        display.setCurrent(form);
    }

    private void manageException(Exception e){
        Alert aux=new Alert("Exception", e.toString(), null, null);
        aux.setTimeout(Alert.FOREVER);
        display.setCurrent(aux);
        e.printStackTrace();
    }
}
